/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*   
 * ChatFrame.java
 *
 * Created on 03/19/2009, 08:47:31 PM
 */
package org.general.chat;
   

import org.mybeans.Sesion;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
 import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

/**
 *
 * @author avbravo
 */
public class ChatFrame extends javax.swing.JFrame implements MessageListener {

    ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
    XMPPConnection connection = new XMPPConnection(config);
    Chat chat;
    Persistencia persistencia;
    Sesion sesion;
    boolean mostrarRecibido = false;

    /** Creates new form ChatFrame */
    public ChatFrame() {
        initComponents();
        /*
         * Fondo
         */

        
          
         

         
         

        /*
         * fin del fondo
         */
        persistencia = new Persistencia();
        sesion = new Sesion();
        jButtonEnviar.setEnabled(false);
        String usuario = sesion.getMunicipio().toLowerCase() + ".municipio";
        jTextFieldUsuario.setText(usuario);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldUsuario = new javax.swing.JTextField();
        jPasswordField1 = new javax.swing.JPasswordField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextFieldMensaje = new javax.swing.JTextField();
        jButtonEnviar = new javax.swing.JButton();
        jInternalFrame1 = new javax.swing.JInternalFrame();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaMensajes = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Chat");
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });

        jLabel1.setText("Usuario");

        jLabel2.setText("Password");

        jTextFieldUsuario.setText("macaracas.municipio");
        jTextFieldUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldUsuarioActionPerformed(evt);
            }
        });

        jPasswordField1.setText("macaracas16");
        jPasswordField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordField1ActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/chatconectar.jpeg"))); // NOI18N
        jButton1.setToolTipText("Conectar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButton2.setToolTipText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextFieldMensaje.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldMensajeActionPerformed(evt);
            }
        });

        jButtonEnviar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/chatenviar.jpeg"))); // NOI18N
        jButtonEnviar.setToolTipText("Enviar");
        jButtonEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEnviarActionPerformed(evt);
            }
        });

        jInternalFrame1.setVisible(true);

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        jTextAreaMensajes.setColumns(20);
        jTextAreaMensajes.setRows(5);
        jScrollPane1.setViewportView(jTextAreaMensajes);

        javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
        jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
        jInternalFrame1Layout.setHorizontalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jInternalFrame1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)
                .addGap(46, 46, 46))
        );
        jInternalFrame1Layout.setVerticalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jInternalFrame1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(223, Short.MAX_VALUE))
        );

        jLabel3.setText("Mensaje");

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/chatlistacontactos.jpeg"))); // NOI18N
        jButton3.setToolTipText("Contactos");
        jButton3.setEnabled(false);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(32, 32, 32)
                        .addComponent(jTextFieldUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(20, 20, 20)
                                .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldMensaje, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jButtonEnviar, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(90, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jTextFieldUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jButton1)))
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(jTextFieldMensaje, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButtonEnviar)
                    .addComponent(jButton3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(61, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            // TODO add your handling code here:
            Conectar();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error  " + ex.getMessage(), "ComboBox SubGrupoRegimen ActionPerformed", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButtonEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEnviarActionPerformed
        try {
            // TODO add your handling code here:
            Enviar();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error  " + ex.getMessage(), "Boton Enviar", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButtonEnviarActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        Desconectar();
        dispose();

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jTextFieldUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldUsuarioActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_jTextFieldUsuarioActionPerformed

    private void jTextFieldMensajeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldMensajeActionPerformed
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:
            Enviar();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error  " + ex.getMessage(), "JTextField Mensajes", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jTextFieldMensajeActionPerformed

    private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
        // TODO add your handling code here:
        try {


            if (mostrarRecibido == true) {
                jTextAreaMensajes.append(persistencia.getMensaje() + "\n");
                mostrarRecibido = false;
            } else {

                jTextAreaMensajes.append(persistencia.getMensaje() + "\n");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error  " + ex.getMessage(), "WindowsGained()", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_formWindowGainedFocus

    private void jPasswordField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordField1ActionPerformed
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:
            Conectar();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error  " + ex.getMessage(), "JPasswordField", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jPasswordField1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        Contactos();
    }//GEN-LAST:event_jButton3ActionPerformed
    private void Desconectar() {
        connection.disconnect(); //Disconnect


    }

    private void Enviar() {
        try {
            String msg;

            msg = jTextFieldMensaje.getText();
            jTextFieldMensaje.setText("");
            jTextAreaMensajes.append(jTextFieldUsuario.getText().toString() + " -> " + msg + "\n");

            chat.sendMessage(msg); /* Send the message */
        } catch (XMPPException ex) {
            JOptionPane.showMessageDialog(this, "Verifique el usuario y password\nNo se puede conectar\nError: " + ex.getMessage(), "Error en conexion", JOptionPane.ERROR_MESSAGE);

        } catch (Exception iox) {
            JOptionPane.showMessageDialog(this, "Verifique el usuario y password\nNo se puede conectar\nError: " + iox.getMessage(), "Error en conexion", JOptionPane.ERROR_MESSAGE);
        }

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ChatFrame().setVisible(true);
            }
        });
    }

    public void processMessage(Chat chat, Message message) /*Callback method from MessageListener interface . It is called when a message is received */ {
        try {
            persistencia.setMensaje(chat.getParticipant() + " : " + message.getBody());
            jTextAreaMensajes.append(chat.getParticipant() + " : " + message.getBody());

            // JOptionPane.showMessageDialog(this, chat.getParticipant() + " : \nMensaje: " + message.getBody(), "Respuesta", JOptionPane.INFORMATION_MESSAGE);
            mostrarRecibido = true;



            WaitWind waitWind = new WaitWind();
            waitWind.setVisible(true);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error:  " + ex.getMessage(), "processMessage()", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void Conectar() throws XMPPException, IOException {

        String username = this.jTextFieldUsuario.getText();
        if (username == null || username.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el nombre del usuario", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String password = new String(this.jPasswordField1.getPassword());

        if (password == null || password.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el password del usuario", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        /*Login to GTalk service*/


        connection.connect(); /* Connect to the XMPP server */
     
        connection.login(username, password); /*Enter your username & password to login to the gtalk service */

        /*Start the chat client */
        chat = connection.getChatManager().createChat("avbravo@gmail.com", new ChatFrame()); /* Replace friend , with your buddies id */
        //   chat = connection.getChatManager().createChat(contactochatear, new ChatFrame()); /* Replace friend , with your buddies id */
        // Get the user's roster

        jTextAreaMensajes.setText("Conectado exitosamente\n");

        jButtonEnviar.setEnabled(true);
    //  Contactos();

    }

    private void Contactos() {
        try {
            Roster roster = connection.getRoster();

            // Print the number of contacts
            jTextAreaMensajes.append("Numero de Contactos: " + roster.getEntryCount() + "\n");
            //  System.out.println("Number of contacts: " + roster.getEntryCount());

            // Enumerate all contacts in the user's roster
//            jComboBoxContactos.removeAllItems();
            int count = 0;
            for (RosterEntry entry : roster.getEntries()) {
                //System.out.println("User: " + entry.getUser());
                jTextAreaMensajes.append("Contacto: " + entry.getUser() + "\n");
                String contacto = entry.getUser();
                //              jComboBoxContactos.insertItemAt(contacto, count);
                count++;
            }
            if (count != 0) {
                //jComboBoxContactos.setSelectedIndex(0);
                //jComboBoxContactos.setSelectedItem("avbravo@gmail.com");
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage(), "Contactos()", JOptionPane.ERROR_MESSAGE);
        }

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButtonEnviar;
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextAreaMensajes;
    private javax.swing.JTextField jTextFieldMensaje;
    private javax.swing.JTextField jTextFieldUsuario;
    // End of variables declaration//GEN-END:variables
}
